package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.mapper.UserExtMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class PaidanController {

    private static final Logger logger = LoggerFactory.getLogger(PayController.class);

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IPyqService pyqService;
    @Autowired
    private IQnpay qnpay;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private IAccountFlowService accountflowService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private UserExtMapper userExtMapper;

    /*申请接单员
     *@param money:押金金额
     *
     */
    @RequestMapping("/api/user/jiedanyuansq")
    @ResponseBody
    public Jinfo jiedanyuansq(@RequestParam("money") BigDecimal money,
                              @RequestParam("name") String name,
                              @RequestParam("phone") String phone,
                              @RequestParam("weixin") String weixin,
                              @RequestParam("carda") String carda,
                              @RequestParam("cardb") String cardb,
                              HttpServletRequest req) {
        Jinfo json = new Jinfo();

        Long mid = ObjectUtil.getMid();
        Long uid = ObjectUtil.getUid();

        BigDecimal zero = new BigDecimal(0);
        User user = userService.selectById(uid);
        if (user == null) {
            json.setCode(4);
            json.setMsg("用户未登陆或不存在");
            return json;
        }
        int cot = orderService.selectCount(new EntityWrapper<Order>()
                .eq("status", 3)
                .eq("mpid", ObjectUtil.getMpid())
                .eq("uid", ObjectUtil.getUid())
                .eq("xftype", XftypeEnum.jyajin.getVal())
        );
        if (cot > 0) {
            json.setCode(1);
            json.setMsg("申请接单员正在审核中请勿重复提交");
            return json;
        }
        Order order = new Order();

        Address address = addressService.selectOne(new EntityWrapper<Address>().eq("uid", uid).eq("is_default", 1));
        if (address != null) {
            order.setLinkman(address.getLinkman());
            order.setPhone(address.getPhone());
            order.setAddress(address.getAddress());
        } else {
            order.setLinkman(user.getNickName());
            order.setPhone(user.getPhone() == null ? "" : user.getPhone());
            order.setAddress(user.getCity() == null ? "" : user.getCity());
        }
        logger.info("===========jyajin order=" + JSON.toJSONString(order));

        order.setOrderNo(StringUtil.getSnNo("Y"));
        order.setPayType(PaytypeEnum.weixin.getVal());
        order.setGoodsName("申请接单员交纳押金");
        order.setPrices(money);
        order.setTotal(money);
        order.setDiscount(zero);
        order.setRealpay(money);
        order.setIsNeedLogistics(0);
        order.setStatus(StatusEnum.forpay.getVal());
        order.setState(1);
        order.setDeduction(zero);
        order.setOrderType(0);
        order.setGoodsNumber(1);

        order.setLinkman(name);
        order.setPhone(phone);
        order.setHeadimg(user.getAvatarPic());

        order.setXftype(XftypeEnum.jyajin.getVal());
        order.setGtype(GtypeEnum.xu.getVal());
        order.setType(YXType.common.getVal());//营销类型@ 0：普通商品； 1：拼团；2：砍价；3：抽奖；4：积分购；5：会员商品
        order.setXftype(XftypeEnum.jyajin.getVal());//营销类型@ 0：普通商品； 1：拼团；2：砍价；3：抽奖；4：积分购；5：会员商品
        order.setUid(uid);
        order.setMid(mid);
        order.setMpid(ObjectUtil.getMpid());
        order.setFantimeType(null);
        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        order.insert();


        //更新用户信息
        user.setPhone(phone);
        user.setName(name);
        user.setWeixin(weixin);

        UserExt ue = userExtMapper.selectById(user.getId());
        ue.setCarda(carda);
        ue.setCardb(cardb);
        ue.setUid(user.getId());
        ue.insertOrUpdate();

        user.setIsStaff(0);
        user.updateById();

        redisService.delUser();

        json.setInfo(orderService.getPaymap(order, false, "在线交纳押金"));

        return json;
    }

    /*
     * 派单撤销
     */
    @RequestMapping("/api/order/pdcancel")
    @ResponseBody
    public Jinfo cancelPyqOrder(@RequestParam("orderNo") String orderNo) {
        Jinfo json = new Jinfo();
        Map<String, Object> map = null;
        if (Strings.isNullOrEmpty(orderNo)) {
            json.setCode(1);
            json.setMsg("参数错误");
            return json;
        }
        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("order_no", orderNo));
        if (order == null) {
            json.setCode(4);
            json.setMsg("该订单不存在");
            return json;
        }
        // 商家秒退
        if (order.getStatus() < 1 || order.getStatus() > 3) {
            json.setCode(1);
            json.setMsg("当前不支持取消订单操作");
            return json;
        }

        if (Strings.isNullOrEmpty(order.getRefundNo())) {
            order.setRefundNo(StringUtil.getSnNo("R"));
            order.setIsRefund(1);
        }
        // 生成订单取消申请
        OrderRefund or = new OrderRefund();
        or.setRealpay(order.getRealpay());
        or.setRefund(order.getRealpay());
        or.setOid(order.getId());
        or.setOrderNo(order.getOrderNo());
        or.setRefundNo(order.getRefundNo());
        or.setRemark("取消派单订单");
        or.setStatus(1);// 默认受理中
        or.setState(1);

        String ip = ObjectUtil.getIP();
        or.setIp(ip);// 默认受理中

        or.setUid(order.getUid());
        or.setMid(order.getMid());
        or.setMpid(order.getMpid());
        or.setCreatetime(new Date());
        or.insert();

        order.setStatus(-1);
        order.updateById();

        Pyq pyq = pyqService.selectById(order.getGid());
        pyq.setStatus(0);
        pyq.setModifier(ObjectUtil.getUid());
        pyq.setModifytime(new Date());
        pyq.updateById();

        order.updateById();

        qnpay.cancelOrder(order, ObjectUtil.getAppid());

        Long jduid = order.getJduid();
        if (jduid != null) {
            AccountFlow af = accountflowService.selectOne(new EntityWrapper<AccountFlow>()
                    .eq("sn", order.getOrderNo()).eq("uid", jduid)
                    .eq("iotype", IotypeEnum.input.getVal())
                    .eq("xftype", XftypeEnum.jiedanyongji.getVal()));

            if (af == null) return json;
            af.setId(null);
            af.setIotype(IotypeEnum.output.getVal());
            af.setXftype(XftypeEnum.refundFanliing.getVal());
            af.setXftypename(XftypeEnum.refundFanliing.getName());
            af.setIsConfirm(-1);
            af.setConfirmDate(null);
            accountService.addAccountOutFlow(af);
        }

        return json;
    }

    @RequestMapping("/api/order/zuodanok")
    @ResponseBody
    public Jinfo zuodanok(long id,Integer xing) {
        Jinfo json = new Jinfo();

        Order order = orderService.selectOne(new EntityWrapper<Order>()
                .eq("gid", id)
                .eq("xftype", XftypeEnum.paidan.getVal())
        );
        if (order == null) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }
        order.setXing(xing);
        qnpay.updateOrderStatus(order, StatusEnum.finish.getVal());
        Order o1 = orderService.selectOne(new EntityWrapper<Order>().setSqlSelect("avg(xing) as xingping")
                .eq("xftype",XftypeEnum.paidan.getVal())
                .gt("status",1).eq("jduid",order.getJduid()));
        User jduser = new User();
        jduser.setId(order.getJduid());
        jduser.setModifier(order.getUid());
        jduser.setModifytime(new Date());
        jduser.setXing(o1.getXingping());

        AccountFlow af = accountflowService.selectOne(new EntityWrapper<AccountFlow>()
                .eq("mpid", ObjectUtil.getMpid())
                .eq("sn", order.getOrderNo())
                .eq("xftype", XftypeEnum.jiedanyongji.getVal())
                .eq("uid", order.getJduid())
        );

        if (af == null) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }

        accountService.ruzhangFromAF(af);

        return json;
    }

    /*
     * 我的接单
     */
    @RequestMapping("/api/order/jdlist")
    @ResponseBody
    public Jinfo jdlist(@RequestParam(value = "pageIndex", required = false) int pageIndex,
                        @RequestParam(value = "pageSize", required = false) int pageSize,
                        @RequestParam(value = "status", required = false) int status,
                        HttpServletRequest req) {
        Jinfo json = new Jinfo();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("mid", req.getSession().getAttribute("mid"));

        Page page = new Page(pageIndex, pageSize);

        Wrapper<Order> en = new EntityWrapper<Order>()
                .ne("is_deleted", 1)
                .eq("state", 1)
                .eq("jduid", ObjectUtil.getUid());

        if (status != 99) en.eq("status", status);
        en.orderBy("id", false);

        page = orderService.selectPage(page, en);

        if (page.getRecords().size() == 0) {
            json.setCode(0);
            json.setMsg("no data found");
            return json;
        }

        List<Order> olist = page.getRecords();
//        String rkey = null;
//        for(Order item:olist){
//            if(item.getJduid()!=null){
//                User jduser = userService.selectById(item.getJduid());
//                item.setJdname(jduser.getName());
//                item.setJdphone(jduser.getPhone());
//            }
//        }
        json.setInfo(olist);
        return json;
    }

    //我的派单列表
    @RequestMapping("/api/order/mypdlist")
    @ResponseBody
    public Jinfo mypdlist() {
        Jinfo jinfo = new Jinfo();
        List<Order> list = orderService.selectList(new EntityWrapper<Order>()
                .eq("xftype", XftypeEnum.paidan.getVal())
                .eq("jduid", ObjectUtil.getUid())
        );
        jinfo.setInfo(list);
        return jinfo;
    }

}
